package connect_to_database;

import com.mysql.cj.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Queue;

public class JDBCUtil {
    private static Queue<Connection> pool = new LinkedList<>();
    private static Driver driver;
    static{
        try {
            driver = new com.mysql.cj.jdbc.Driver();
            //注册驱动类
            DriverManager.registerDriver(driver);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    private static String url="jdbc:mysql://localhost:3306/sqldemo?serverTimezone=GMT&useSSL=True";
    private static String username="root";
    private static String password="123456";
    public static synchronized Connection getConnection() {
        if (pool.size() == 0) {
            try {
                pool.add(DriverManager.getConnection(url, username, password));
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return pool.poll();
    }

    public static synchronized void release(Connection connection) {
        pool.add(connection);
    }
}
